<?php

class Page_IndexController extends Zend_Controller_Action
{

    public function init()
    {
        Zend_Registry::get('layout')->setLayout('node');
        
        $activeResource=Page_Model_Page::RESOURCE_NAME;
        
        // seting active resource
        Zend_Registry::set('resource',$activeResource);

        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->flash_messages = $this->_flashMessenger->getMessages();
    }

    public function indexAction()
    {
        $alias=(string) $this->_getParam('alias');
        
        if (!Zend_Registry::get('user')->canView() || empty($alias))
        {
            return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
        }

        if (preg_match('/(.+)\.html$/',$alias,$matches))
        {
            $alias=$matches[1];
        }

        $cache=Zend_Registry::get('cache');
        
        if(!$nodes = $cache->load('page_'.md5($alias))) 
        {
            $nodeTbl=new Application_Model_NodeDb();
            
            $nodes=$nodeTbl->fetchNodesByClause(array('url_alias=?'=>$alias,'type=?'=>'node','published=?'=>'1'));
            
            $cache->save($nodes, 'page_'.md5($alias));
        }
        
        if (empty($nodes))
        {
            $this->_helper->FlashMessenger(Zend_Registry::get('locale')->_('Page not found'));
            
            return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
        }
        
        $authors=array();
        
        $userTbl=new Application_Model_UserDb();
        
        $first=true;
        foreach ($nodes as $nodeObj)
        {
            $userObj=$userTbl->fetchUserById($nodeObj->uid);
            
            $authors[$nodeObj->uid]=$userObj;
            
            if ($first)
                $this->view->headTitle()->set($nodeObj->title);
            else 
                $this->view->headTitle()->append($nodeObj->title);
                
            $this->view->headMeta()->appendName('keywords', $nodeObj->getKeywords())
                                   ->appendName('description', $nodeObj->getDescription());
        }
        
        $this->view->nodes=$nodes;
        $this->view->authors=$authors;
    }


}

